/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fsd.semana3.aula.echoeventlinhas;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author nfsa
 */
public class Echo {

    private SelectionKey key;
    private List<String> list;
    private ByteBuffer bufferTmp = ByteBuffer.allocate(256);
    private boolean readMessage = false;
    private LineListener listener;
    private ByteChannel ch;
    private DataInputStream inputStream;
    private DataOutputStream outputStream;

    public Echo(SelectionKey _key) {
        list = new ArrayList<String>(100);
        key = _key;
        this.ch = (ByteChannel) key.channel();

    }

    public void setListener(LineListener listener) {
        this.listener = listener;
    }

    public void handleRead() throws IOException {

        ByteBuffer bfTmp = ByteBuffer.allocate(256);
        if (!readMessage) {
            bufferTmp.clear();
            if (ch.read(bufferTmp) <= 0) {
                return;
            }
            bufferTmp.flip();
        }

        while (bufferTmp.hasRemaining()) {
            byte next = bufferTmp.get();
            if (next == 10) { // New line
                bfTmp.flip();
                String line = Charset.defaultCharset().decode(bfTmp).toString();
                bfTmp.clear();
                writeLine(line);
                if (listener != null) {
                    listener.onReadLine(line);
                }
            } else if (next != 13) // Carriage return
            {
                bfTmp.put(next);
            }
        }
        readMessage = false;

        if (list.size() > 100) {
            key.interestOps(SelectionKey.OP_WRITE);
        } else {
            key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
        }
    }

    public void handleWrite() throws IOException {
        
        if (list.isEmpty()) {
            key.interestOps(SelectionKey.OP_READ);
        } else {
            ByteBuffer buffer = Charset.defaultCharset().encode(list.remove(0));
            SocketChannel  channel =(SocketChannel) key.channel();
            channel.write(buffer);
            
            key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
        }
    }

    public void writeLine(String line) {
		list.add(line);
		key.interestOps(SelectionKey.OP_READ|SelectionKey.OP_WRITE);
    }
}
